/*
 * ImageManager.cpp
 * This file is part of Dragon and Weed 2 
 *
 * Copyright (C) 2011 - François Berder
 *
 * Dragon and Weed 2 is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * Dragon and Weed 2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
 
 

#include "ImageManager.hpp"
#include "Logger.hpp"
#include "Path.hpp"


ImageManager::ImageManager()
{
}
ImageManager::~ImageManager()
{
}

ImageManager& ImageManager::instance()
{
	static ImageManager i;
	return i;
}


bool ImageManager::loadRessource(RessourceDef& resDef)
{
	// check file
	Path p(resDef.m_name);
	if(!p.isValid())
	{
		LogErr << "Unable to load image : "<< p.fileName() << ".Reason : this file is not valid." << LogEnd; 
		return false;
	}
	
	// load image
	sf::Image *i = new sf::Image;
	if(i->LoadFromFile(resDef.m_name))
	{
		LogInfo << "Image " << resDef.m_name << " loaded with success." << LogEnd;
		RessourceDef def(resDef.m_name); // avoid to take in account m_size
		m_ressources[def] = ImagePtr(i);
		return true;
	}
	else
	{
		delete i;
		LogErr << "Unable to load image : " << resDef.m_name << ". Reason : fail to load image." << LogEnd;
		return false; 
	}
}

bool ImageManager::loadRessourceFromMemory(const std::string& name, char* data, const size_t size)
{
	if(m_ressources.find(name) != m_ressources.end())
	{
		LogInfo << "Image " << name << " already loaded." << LogEnd;
		return true;
	}
	
	sf::Image *i = new sf::Image;
	if(i->LoadFromMemory(data,size))
	{
		LogInfo << "Image " << name << " loaded with success from memory." << LogEnd;
		RessourceDef def(name);	
		m_ressources[def] = ImagePtr(i);
		return true;
	}
	else
	{
		delete i;
		LogErr << "Unable to load image : " << name << ". Reason : fail to load image." << LogEnd;
		return false; 
	}	
}
